<?php
/**
 * Created by PhpStorm.
 * User: Aliaksei Lazerka
 * Date: 10/3/14
 * Time: 10:56 PM
 */

namespace mysql;

if (!defined('NYMPH_ROOT')) {
  define('NYMPH_ROOT', dirname("../../../" . __FILE__));
  require(NYMPH_ROOT . '/local/loader/kernel/classes/URLClassLoader.php');
}

use base\IDBActions;

class MySQLDBActions implements IDBActions
{

  /**
   * @var string db encoding
   */
  private $encoding;

  /**
   * @global string
   */
  const ENCODING = 'utf8';

  /**
   * If encoding is empty, then it will be changed to default encoding
   * @param $encoding [optional]
   */
  function __construct($encoding)
  {
    if (!$encoding) {
      $this->encoding = self::ENCODING;
    } else {
      $this->encoding = $encoding;
    }
  }

  /**
   * (PHP 5)<br/>
   * Execute sql query
   * @param string $query
   * @return mixed query result or false if query failed
   */
  public function executeStringQuery($query)
  {
    return mysql_query($query);
  }

  /**
   * (PHP 5)<br/>
   * Get error occurred
   * @return string error
   */
  public function getQueryError()
  {
    return mysql_error();
  }

  /**
   * (PHP 5)<br/>
   * Connect to db
   * @param string $url
   * @param string $db
   * @param string $user
   * @param string $password
   * @return mixed link id
   */
  public function connectToDB($url, $db, $user, $password)
  {
    $linkId = mysql_connect($url, $user, $password);
    mysql_select_db($db, $linkId);
    mysql_query("SET NAMES '" . $this->encoding . "'");
    mysql_query("SET CHARACTER SET '" . $this->encoding . "'");
    return $linkId;
  }

  /**
   * (PHP 5)<br/>
   * Close database connection
   * @return bool
   */
  public function closeConnection()
  {
    return mysql_close();
  }
}